<?php

namespace App\Console\Commands;

use App\Models\Admin\Supplier;
use App\Models\Admin\Supplier as SupplierModel;
use App\Models\Admin\SupplierConfiguration;
use App\Models\Mysql\XnMechantBalance;
use App\Models\Mysql\XnMerchant;
use Illuminate\Console\Command;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Database\Eloquent\Collection;

class ZeroBalance extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:zero-balance';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle()
    {
//        Supplier::query()->where('account_verification', 1)->get()->map(function(Supplier $supplier) {
//            // 商户map
//            XnMerchant::sr($supplier)->chunk(200, function(Collection $collection) use ($supplier) {
//                $data = [];
//                $collection->map(fn(XnMerchant $merchant) => array_push($data, [
//                    'merchant_number' => $merchant->merchant_number,
//                    'balance'         => $merchant->balance,
//                    'merchant_type'   => 1,
//                    'ctime'           => date('Y-m-d')
//                ]));
//                Log::channel('task')->info(sprintf(
//                    '%s-%s-库商户余额信息添加%s',
//                    date('Y-m-d'),
//                    dbConnectKey($supplier),
//                    XnMechantBalance::s($supplier)->insert($data) ? '成功' : '失败',
//                ));
//            });
//        });
        $supplier_info = Supplier::query()->where('account_verification', 1)->get() -> toArray();
        foreach($supplier_info as $k => $v){
            $connect = dbRegister($v['id']);
            $merchant_info = DB::connection($connect)->table('xn_merchant')->select('Merchant_number','balance') -> get() -> toArray();
            if(!$merchant_info){
                Log::channel('task')->info(date('Y-m-d')."零点余额统计失败，未查询到商户\r\n");
            }
            $infos = [];
            foreach($merchant_info as $k => $value){
                $infos[] = [
                    'merchant_number' => $value['Merchant_number'],
                    'balance' => $value['balance'],
                    'merchant_type' => 1,
                    'ctime' => date('Y-m-d',time())
                ];
            }
            $res = DB::connection($connect) -> table('xn_mechant_balance')->insert($infos);
            if($res){
                Log::channel('task')->info(date('Y-m-d').$connect."库商户余额信息添加成功\r\n");
            }else{
                Log::channel('task')->info(date('Y-m-d').$connect."库商户余额信息添加失败\r\n");
            }
        }

    }
}
